<template>
  <div class="portal-login">
    <div class="login-container">
      <div class="login-box">
        <div class="login-header">
          <h2>欢迎登录</h2>
          <p>智慧医疗服务平台</p>
        </div>
        
        <el-form 
          ref="formRef"
          :model="loginForm" 
          :rules="loginRules" 
          class="login-form"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username"
              placeholder="请输入用户名/邮箱"
              prefix-icon="User"
              size="large"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              size="large"
              show-password
              clearable
            />
          </el-form-item>
          
          <div class="login-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false" @click="forgotPassword">忘记密码?</el-link>
          </div>
          
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="loading" 
              class="login-button"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="login-footer">
          <p>还没有账号？ <el-link type="primary" :underline="false" @click="toRegister">立即注册</el-link></p>
          <p class="back-to-home">
            <el-link type="info" :underline="false" @click="backToHome">
              <el-icon><ArrowLeft /></el-icon> 返回首页
            </el-link>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 获取重定向地址
const redirectPath = ref('')

onMounted(() => {
  // 从URL参数中获取重定向路径
  if (route.query.redirect) {
    redirectPath.value = route.query.redirect.toString()
  }
  
  // 如果有Token但验证失败，清除Token并提示用户
  if (userStore.token && !userStore.isLoggedIn) {
    userStore.logout()
    ElMessage.error('登录已过期，请重新登录')
  }
  
  // 恢复保存的用户名
  const savedUsername = localStorage.getItem('remember_username')
  if (savedUsername) {
    loginForm.value.username = savedUsername
    rememberMe.value = true
  }
})

// 登录相关状态
const loading = ref(false)
const rememberMe = ref(false)
const formRef = ref(null)

// 账号登录表单
const loginForm = ref({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名/邮箱', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 账号登录
const handleLogin = () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        // 调用登录API
        await userStore.login({
          username: loginForm.value.username,
          password: loginForm.value.password
        })
        
        ElMessage.success('登录成功')
        
        // 如果勾选了"记住我"，将凭据保存到localStorage
        if (rememberMe.value) {
          localStorage.setItem('remember_username', loginForm.value.username)
          // 注意：出于安全考虑，不要存储密码
        } else {
          localStorage.removeItem('remember_username')
        }
        
        // 触发自定义用户登录事件
        window.dispatchEvent(new Event('user-login'))
        
        // 根据角色决定跳转目标
        if (userStore.userRole === 'admin') {
          // 管理员登录后，跳转到系统管理页面
          router.push('/system/users')
        } else {
          // 普通用户登录后，跳转到门户首页
          router.push('/portal')
        }
      } catch (error) {
        console.error('登录失败:', error)
        // 显示更具体的错误信息
        if (error.response && error.response.data) {
          if (error.response.data.message) {
            ElMessage.error(error.response.data.message)
          } else if (error.response.status === 401) {
            ElMessage.error('用户名或密码错误')
          } else {
            ElMessage.error('登录失败，请稍后重试')
          }
        } else {
          ElMessage.error('登录失败，请检查网络连接')
        }
      } finally {
        // 确保在成功或失败时都重置loading状态
        loading.value = false
      }
    }
  })
}

// 忘记密码
const forgotPassword = () => {
  ElMessage.info('忘记密码功能开发中...')
}

// 跳转到注册页
const toRegister = () => {
  router.push('/portal/register')
}

// 返回首页
const backToHome = () => {
  router.push('/portal')
}
</script>

<style scoped>
.portal-login {
  min-height: 100vh;
  background: linear-gradient(to right, #e6f7ff, #f0f9ff);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 1200px;
  display: flex;
  justify-content: center;
}

.login-box {
  width: 450px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.login-header p {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.login-form {
  margin-top: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.login-footer {
  margin-top: 30px;
  text-align: center;
}

.login-footer p {
  margin: 10px 0;
  color: #666;
}

.back-to-home {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .login-box {
    width: 100%;
    max-width: 450px;
    padding: 30px 20px;
  }
}
</style> 